package com.yds.camerax

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.view.View
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import java.io.File

class CameraxCaptureActivity : AppCompatActivity() , CameraCallBack, OnCameraStatusChangeListener {
    // 0-picture 1-video
    private var cameraStyle = 0
    private var cameraXFragment: CameraXFragment? = null
    private var cameraXUIFragment: CameraXUIFragment? = null

    companion object {
        const val CAMERA_FILE_PATH = "CAMERA_FILE_PATH"
        const val CAMERA_STYLE = "CAMERA_STYLE"
        const val CAMERA_STYLE_PICTURE = 0
        const val CAMERA_STYLE_VIDEO = 1
        private const val RESULT_REQUEST_CODE = 9

        fun setArguments(context: FragmentActivity, cameraStyle: Int) {
            val bundle = Bundle()
            bundle.putInt(CAMERA_STYLE, cameraStyle)
            val intent = Intent(context, CameraxCaptureActivity::class.java)
            intent.putExtras(bundle)
            context.startActivityForResult(intent, RESULT_REQUEST_CODE)
        }

        private val PERMISSIONS_REQUIRED = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )

        private const val PERMISSIONS_REQUEST_CODE = 10

        fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): String? {
            data?.let {
                if (resultCode == RESULT_OK) {
                    if (requestCode == RESULT_REQUEST_CODE) {
                        val extras = data.extras
                        extras?.let {
                            return it.getString(CAMERA_FILE_PATH, "")
                        }
                    }
                }
            }
            return null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_camerax_capture)

        val extras = intent.extras
        extras?.let {
            cameraStyle = it.getInt(CAMERA_STYLE, 0)
        }

        if (!hasPermissions(this)) {
            requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
        } else {
            initFragment()
        }
    }

    private fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
        ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (PackageManager.PERMISSION_GRANTED == grantResults.firstOrNull()) {
                initFragment()
            } else {
                Toast.makeText(this, "Permission request denied", Toast.LENGTH_LONG).show()
                if (!hasPermissions(this)) {
                    requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
                }
            }
        }
    }

    private fun initFragment() {
        cameraXFragment = CameraXFragment.createCameraXFragment()
        cameraXFragment?.initCameraFaceDirection(CameraSelector.LENS_FACING_BACK)
        cameraXFragment?.setOnCameraStatusChangeListener(this)
        HelperUtils.replaceFragment(this, R.id.mFlCameraController, cameraXFragment)

        cameraXUIFragment = CameraXUIFragment.createCameraXUIFragment(this, cameraStyle)
        HelperUtils.replaceFragment(this, R.id.mFlCameraUIController, cameraXUIFragment)
    }


    override fun onResume() {
        super.onResume()
        window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE or
                View.SYSTEM_UI_FLAG_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    }

    override fun switchCameraFace() {
        cameraXFragment?.switchCameraFace()
    }

    override fun switchCameraMode(type: Int) {
        cameraXFragment?.switchCameraMode(type)
    }

    override fun switchCameraFlash() {
        cameraXFragment?.switchCameraFlash()
    }

    override fun takeCamera() {
        cameraXFragment?.takeCapture(takeCaptureCallBack = object : CameraTakeCaptureCallBack {
            override fun takeCaptureCallBack(picFile: File?, picUri: Uri?) {
//                Log.i("YDSimon", "takeCaptureCallBack = " + picFile?.absolutePath)
                val bundle = Bundle()
                bundle.putString(CAMERA_FILE_PATH, picFile?.absolutePath)
                val intent = Intent()
                intent.putExtras(bundle)
                setResult(RESULT_OK, intent)

                finish()
            }
        })
    }

    override fun startRecordVideo() {
        cameraXFragment?.startRecordVideo(object :CameraTakeVideoCallBack{
            override fun takeVideoCallBack(videoFile: File?, videoUri: Uri?) {
//                Log.i("YDSimon", "takeVideoCallBack = " + videoFile?.absolutePath)
                val bundle = Bundle()
                bundle.putString(CAMERA_FILE_PATH, videoFile?.absolutePath)
                val intent = Intent()
                intent.putExtras(bundle)
                setResult(RESULT_OK, intent)

                finish()
            }
        })
    }

    override fun stopRecordVideo() {
        cameraXFragment?.stopRecordVideo()
    }

    override fun onStartRecord() {
        cameraXUIFragment?.startRecord()
    }

    override fun onStopRecord() {
        cameraXUIFragment?.stopRecord()
    }

    override fun onToggleCameraFace(lensFacing: Int) {
    }

}